import { log } from 'console';
/**
 *@auther: tang
 *@Date: 2021-01-29
 *Project: p2pPlatformSys
 *Lang: TypeScript
 */

const dayjs = require('dayjs');
const fs = require('fs');
const path = require('path');
const { Op } = require('sequelize');
export function getNowTime() {
  const time = new Date();
  return `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()} ${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`;
}
export function calcFileHref(fileNameInp:string) {
  const uplaodBasePath = 'app/public/upload/';
  // 生成文件名
  const filename:string = Date.now() + '' + Number.parseInt(String(Math.random() * 10000)) + path.extname(fileNameInp);
  // 生成文件夹
  const dirName = dayjs(Date.now()).format('YYYYMMDD');
  // 判断文件夹是否存在，不存在则直接创建文件夹
  if (!fs.existsSync(path.join(uplaodBasePath, dirName))) fs.mkdirSync(path.join(uplaodBasePath, dirName));
  // 生成写入路径
  return path.join(uplaodBasePath, dirName, filename);
}
export function generateObjArr(dataParams:object[], dataOrigin:object[]) {
  const origin:object[] = JSON.parse(JSON.stringify(dataOrigin));
  for (const i in origin) {
    if (dataParams[i]) {
      origin[i] = dataParams[i];
    }
  }
  return origin;
}
export function clearObj(oriData:any[]):object[] {
  const origin = JSON.parse(JSON.stringify(oriData));
  for (const oriDataKey in origin) {
    if (typeof origin[oriDataKey] === 'number') {
      origin[oriDataKey] = null;
    } else {
      origin[oriDataKey] = null;
    }
  }
  return origin;
}
export function clearNullItems(oriData:any[]):object[] {
  const origin = JSON.parse(JSON.stringify(oriData));
  for (const oriKey in origin) {
    if (!origin[oriKey]) {
      delete origin[oriKey];
    }
  }
  return origin;
}
export function getDateNumber() {
  const date = new Date();
  const dateNumber = date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate() + '' + date.getHours() + '' + date.getMinutes() + '' + date.getSeconds() + '' + date.getMilliseconds() + '' + date.getTime();
  return dateNumber;
}
export function generateQueryArr(params:object[]) {
  log(params);
  const newPar = JSON.parse(JSON.stringify(params));
  const newArr = [];
  for (const i in newPar) {
    const newObj:any = {};
    newObj[i] = {
      [Op.like]: '%' + newPar[i] + '%',
    };
    newArr.push(newObj as never);
  }
  return {
    [Op.and]: newArr,
  };
}
// export async function logTranscation(ctx, fn1, fn2) {
//   let transaction:any = null;
//   return new Promise(async (resolve, reject) => {
//     try {
//       transaction = await ctx.model.transaction();
//       const data1 = await fn1();
//       const data2 = await fn2();
//       resolve({ msg: '操作成功', code: 200, data1, data2 });
//       await transaction.commit();
//     } catch (e) {
//       reject(e);
//     }
//   });
// }
